"""
MCP 服务器管理路由
提供MCP服务器配置管理的FastAPI路由
"""

from typing import List, Dict, Any, Optional
import os
from fastapi import APIRouter, HTTPException, Body, Path, Query
from pydantic import BaseModel
from src.config.settings import settings
from src.services.mcp_service import mcp_service_manager, MCPServiceError
import asyncio

# 创建路由器
router = APIRouter(prefix="/mcp", tags=["MCP服务器管理"])

# 修复所有导入问题
import src.utils.mcp_plugin_loader
plugin_loader = src.utils.mcp_plugin_loader.plugin_loader  

import src.services.mcp_fastmanager as mcp_fastmanager
fast_register_server = mcp_fastmanager.register_server
fast_unregister_server = mcp_fastmanager.unregister_server
fast_list_servers = mcp_fastmanager.list_servers
fast_get_server_info = mcp_fastmanager.get_server_info
fast_check_health = mcp_fastmanager.check_health
fast_discover_tools = mcp_fastmanager.discover_tools
fast_invoke_tool = mcp_fastmanager.invoke_tool


class MCPServerConfig(BaseModel):
    """MCP服务器配置模型"""
    server: str
    enabled: Optional[bool] = None
    url: Optional[str] = None
    api_key: Optional[str] = None
    timeout: Optional[int] = None
    retries: Optional[int] = None


class MCPConfigUpdate(BaseModel):
    """MCP配置更新模型"""
    enabled: Optional[bool] = None
    servers: Optional[List[str]] = None
    server_config: Optional[MCPServerConfig] = None


class MCPConfigResponse(BaseModel):
    """MCP配置响应模型"""
    enabled: bool
    servers: List[str]
    server_configs: Dict[str, Dict[str, Any]]
    config_source: str = "environment_variables"


class MCPToolCallRequest(BaseModel):
    """MCP工具调用请求模型"""
    server: str
    tool: str
    parameters: Dict[str, Any]


class MCPToolCallResponse(BaseModel):
    """MCP工具调用响应模型"""
    success: bool
    result: Optional[Dict[str, Any]] = None
    error: Optional[str] = None


class MCPToolDescription(BaseModel):
    """MCP工具描述"""
    name: str
    description: str
    parameters: Dict[str, Any]


class PluginOperationResponse(BaseModel):
    """插件操作响应模型"""
    success: bool
    message: str
    plugin: Optional[str] = None
    details: Optional[Dict[str, Any]] = None


class PluginSecurityInfo(BaseModel):
    """插件安全信息模型"""
    plugin_name: str
    has_signature: bool
    signature_valid: Optional[bool] = None
    permissions: List[str]
    allowed: bool


class PluginCacheInfo(BaseModel):
    """插件缓存信息模型"""
    plugin_name: str
    cached: bool
    valid: Optional[bool] = None
    timestamp: Optional[float] = None
    ttl: int


class ServerStatusResponse(BaseModel):
    """服务器状态响应模型"""
    server_name: str
    enabled: bool
    config: Dict[str, Any]
    tools: List[str]
    error: Optional[str] = None


class HealthCheckResponse(BaseModel):
    """健康检查响应模型"""
    server_name: str
    status: str  # healthy, unhealthy, error, unavailable
    message: Optional[str] = None
    details: Optional[Dict[str, Any]] = None


class FastMCPManagerRequest(BaseModel):
    """FastMCP管理请求模型"""
    action: str
    parameters: Dict[str, Any]


class ConfigVersionInfo(BaseModel):
    """配置版本信息模型"""
    version: int
    source: str
    timestamp: str
    checksum: str


class ConfigVersionsResponse(BaseModel):
    """配置版本响应模型"""
    source: str
    versions: List[ConfigVersionInfo]


class ErrorDetailsResponse(BaseModel):
    """错误详情响应模型"""
    error_code: str
    message: str
    details: Optional[Dict[str, Any]] = None
    timestamp: float


class PluginErrorDetailsResponse(BaseModel):
    """插件错误详情响应模型"""
    plugin_name: str
    error_code: str
    message: str
    details: Optional[Dict[str, Any]] = None
    timestamp: float


class PluginFeedbackRequest(BaseModel):
    """插件反馈请求模型"""
    server_name: str
    user_id: str
    feedback: str
    feedback_type: str = "general"  # general, performance, error, suggestion, security
    priority: str = "medium"  # low, medium, high, critical
    metadata: Optional[Dict[str, Any]] = None


class PluginFeedbackResponse(BaseModel):
    """插件反馈响应模型"""
    success: bool
    message: str
    feedback_id: Optional[int] = None
    error: Optional[str] = None


class FeedbackHistoryResponse(BaseModel):
    """反馈历史响应模型"""
    server_name: str
    feedback_list: List[Dict[str, Any]]


class FeedbackProcessRequest(BaseModel):
    """反馈处理请求模型"""
    server_name: str
    strategy: str = "auto"  # auto, ignore, restart, reconfigure
    custom_thresholds: Optional[Dict[str, Any]] = None


class FeedbackProcessResponse(BaseModel):
    """反馈处理响应模型"""
    success: bool
    message: str
    feedback_analysis: Optional[Dict[str, int]] = None
    actions_taken: Optional[List[str]] = None
    error: Optional[str] = None


class FeedbackSummaryResponse(BaseModel):
    """反馈摘要响应模型"""
    server_name: str
    total_feedback: int
    feedback_by_type: Dict[str, int]
    last_feedback: Optional[Dict[str, Any]]


@router.post("/config/reload")
async def reload_mcp_config():
    """
    重新加载MCP配置（热更新）
    
    Returns:
        重新加载结果
    """
    try:
        changed = settings.reload_mcp_configs()
        return {
            "success": True,
            "message": "MCP配置重新加载成功",
            "changed": changed
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"重新加载MCP配置失败: {str(e)}")


@router.post("/config/rollback")
async def rollback_mcp_config(
    source: str = Body(..., embed=True),
    version: int = Body(..., embed=True)
):
    """
    回滚MCP配置到指定版本
    
    Args:
        source: 配置源
        version: 版本号
        
    Returns:
        回滚结果
    """
    try:
        success = settings.rollback_mcp_config(source, version)
        if success:
            return {
                "success": True,
                "message": f"已回滚到配置源 {source} 的版本 {version}"
            }
        else:
            raise HTTPException(status_code=400, detail="配置回滚失败")
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"配置回滚失败: {str(e)}")


@router.get("/config/versions", response_model=Dict[str, ConfigVersionsResponse])
async def get_config_versions(source: Optional[str] = None):
    """
    获取配置版本历史
    
    Args:
        source: 配置源（可选）
        
    Returns:
        配置版本历史
    """
    try:
        # 修复类型不匹配问题，正确处理source为None的情况
        if source is None:
            version_data = settings.get_config_versions()  # 不传递参数，使用默认值
        else:
            version_data = settings.get_config_versions(source)
            
        result = {}
        for src, version_list in version_data.items():
            version_infos = [
                ConfigVersionInfo(
                    version=v.get("version", 0),
                    source=v.get("source", ""),
                    timestamp=v.get("timestamp", ""),
                    checksum=v.get("checksum", "")
                ) for v in version_list
            ]
            result[src] = ConfigVersionsResponse(source=src, versions=version_infos)
        return result
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取配置版本历史失败: {str(e)}")


@router.get("/config/sources")
async def get_config_sources():
    """
    获取支持的配置源列表
    
    Returns:
        配置源列表
    """
    return {
        "sources": [
            "environment",  # 环境变量
            "file",         # 文件
            "database",     # 数据库
            "remote"        # 远程URL
        ],
        "current_source": settings.mcp.CONFIG_SOURCE
    }


@router.get("/plugins/security/{plugin_name}", response_model=PluginSecurityInfo)
async def get_plugin_security_info(plugin_name: str = Path(..., description="插件名称")):
    """
    获取插件安全信息
    
    Args:
        plugin_name: 插件名称
        
    Returns:
        插件安全信息
    """
    try:
        # 获取插件元数据
        metadata = plugin_loader.get_plugin_metadata(plugin_name)
        if not metadata:
            raise HTTPException(status_code=404, detail=f"插件 {plugin_name} 不存在")
        
        # 检查是否有签名
        has_signature = "signature" in metadata
        signature_valid = None
        
        # 验证签名（如果存在）
        if has_signature:
            plugin_path = os.path.join(plugin_loader.plugin_dir, plugin_name)
            plugin_zip_path = os.path.join(plugin_path, "..", f"{plugin_name}_temp", "plugin.zip")
            if os.path.exists(plugin_zip_path):
                with open(plugin_zip_path, 'rb') as f:
                    plugin_data = f.read()
                signature_valid = plugin_loader._verify_plugin_signature(
                    plugin_name, 
                    plugin_data, 
                    metadata["signature"]
                )
        
        # 获取插件权限
        plugin_config = plugin_loader.loaded_plugins.get(plugin_name, {})
        permissions = plugin_config.get("permissions", [])
        
        # 检查插件是否被允许
        allowed = plugin_loader._check_plugin_permissions(plugin_name, plugin_config)
        
        return PluginSecurityInfo(
            plugin_name=plugin_name,
            has_signature=has_signature,
            signature_valid=signature_valid,
            permissions=permissions,
            allowed=allowed
        )
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取插件安全信息失败: {str(e)}")


@router.post("/plugins/verify-signature/{plugin_name}")
async def verify_plugin_signature(plugin_name: str = Path(..., description="插件名称")):
    """
    验证插件签名
    
    Args:
        plugin_name: 插件名称
        
    Returns:
        签名验证结果
    """
    try:
        # 获取插件元数据
        metadata = plugin_loader.get_plugin_metadata(plugin_name)
        if not metadata:
            raise HTTPException(status_code=404, detail=f"插件 {plugin_name} 不存在")
        
        # 检查是否有签名
        if "signature" not in metadata:
            return {
                "plugin": plugin_name,
                "has_signature": False,
                "signature_valid": None,
                "message": "插件无签名信息"
            }
        
        # 获取插件数据
        plugin_path = os.path.join(plugin_loader.plugin_dir, plugin_name)
        # 这里简化处理，实际应该重新下载插件数据进行验证
        plugin_zip_path = os.path.join(plugin_path, "..", f"{plugin_name}_temp", "plugin.zip")
        if not os.path.exists(plugin_zip_path):
            return {
                "plugin": plugin_name,
                "has_signature": True,
                "signature_valid": None,
                "message": "无法获取插件数据进行验证"
            }
        
        with open(plugin_zip_path, 'rb') as f:
            plugin_data = f.read()
        
        # 验证签名
        signature_valid = plugin_loader._verify_plugin_signature(
            plugin_name, 
            plugin_data, 
            metadata["signature"]
        )
        
        return {
            "plugin": plugin_name,
            "has_signature": True,
            "signature_valid": signature_valid,
            "message": "签名验证通过" if signature_valid else "签名验证失败"
        }
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"验证插件签名失败: {str(e)}")


@router.get("/plugins", response_model=Dict[str, Any])
async def list_plugins():
    """
    列出所有插件及其状态
    
    Returns:
        插件列表和状态信息
    """
    try:
        plugins = plugin_loader.list_plugins()
        # 添加插件详细信息
        detailed_plugins = {}
        for plugin_name in plugins:
            detailed_plugins[plugin_name] = plugin_loader.get_plugin_info(plugin_name)
        return detailed_plugins
    except Exception as e:
        raise HTTPException(status_code=400, detail=f"获取插件列表失败: {str(e)}")


@router.get("/plugins/{plugin_name}", response_model=Dict[str, Any])
async def get_plugin_details(plugin_name: str = Path(..., description="插件名称")):
    """
    获取插件详细信息
    
    Args:
        plugin_name: 插件名称
        
    Returns:
        插件详细信息
    """
    try:
        info = plugin_loader.get_plugin_info(plugin_name)
        if not info:
            raise HTTPException(status_code=404, detail=f"插件 {plugin_name} 不存在")
        return info
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=400, detail=f"获取插件信息失败: {str(e)}")


@router.get("/remote-plugins")
async def discover_remote_plugins():
    """
    发现远程插件
    
    Returns:
        远程插件列表
    """
    try:
        remote_plugins = plugin_loader.discover_remote_plugins()
        return {"plugins": remote_plugins}
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"发现远程插件失败: {str(e)}")


@router.post("/plugins/install")
async def install_remote_plugin(
    plugin_name: str = Body(..., embed=True),
    version: Optional[str] = Body(None, embed=True)
):
    """
    从远程仓库安装插件
    
    Args:
        plugin_name: 插件名称
        version: 插件版本（可选）
        
    Returns:
        安装结果
    """
    try:
        success = plugin_loader.install_plugin_from_remote(plugin_name, version)
        if success:
            # 安装成功后自动注册插件
            plugin_loader.register_plugin(plugin_name)
            return {
                "success": True,
                "message": f"插件 {plugin_name} 安装并注册成功",
                "plugin": plugin_name
            }
        else:
            raise HTTPException(status_code=500, detail=f"插件 {plugin_name} 安装失败")
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"安装插件失败: {str(e)}")


@router.get("/plugins/{plugin_name}/metadata")
async def get_plugin_metadata(plugin_name: str = Path(..., description="插件名称")):
    """
    获取插件元数据
    
    Args:
        plugin_name: 插件名称
        
    Returns:
        插件元数据
    """
    try:
        metadata = plugin_loader.get_plugin_metadata(plugin_name)
        if not metadata:
            raise HTTPException(status_code=404, detail=f"插件 {plugin_name} 的元数据不存在")
        return metadata
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取插件元数据失败: {str(e)}")


@router.post("/plugins/{plugin_name}/upgrade")
async def upgrade_plugin(plugin_name: str = Path(..., description="插件名称")):
    """
    升级插件到最新版本
    
    Args:
        plugin_name: 插件名称
        
    Returns:
        升级结果
    """
    try:
        # 获取插件当前元数据
        current_metadata = plugin_loader.get_plugin_metadata(plugin_name)
        if not current_metadata:
            raise HTTPException(status_code=404, detail=f"插件 {plugin_name} 不存在")
        
        # 获取最新版本
        latest_version = current_metadata.get("latest_version")
        if not latest_version:
            raise HTTPException(status_code=400, detail=f"插件 {plugin_name} 无可用更新")
        
        # 检查是否已经是最新版本
        installed_version = current_metadata.get("installed_version")
        if installed_version == latest_version:
            return {
                "success": True,
                "message": f"插件 {plugin_name} 已是最新版本 ({latest_version})",
                "plugin": plugin_name,
                "version": latest_version
            }
        
        # 卸载当前插件
        plugin_loader.unload_plugin(plugin_name)
        
        # 安装最新版本
        success = plugin_loader.install_plugin_from_remote(plugin_name, latest_version)
        if success:
            # 重新注册插件
            plugin_loader.register_plugin(plugin_name)
            return {
                "success": True,
                "message": f"插件 {plugin_name} 已升级到版本 {latest_version}",
                "plugin": plugin_name,
                "version": latest_version
            }
        else:
            raise HTTPException(status_code=500, detail=f"插件 {plugin_name} 升级失败")
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"升级插件失败: {str(e)}")


@router.get("/status", response_model=List[ServerStatusResponse])
async def get_all_servers_status():
    """
    获取所有MCP服务器状态
    
    Returns:
        所有服务器的状态信息
    """
    try:
        statuses = mcp_service_manager.get_all_servers_status()
        return statuses
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取服务器状态失败: {str(e)}")


@router.get("/status/{server_name}", response_model=ServerStatusResponse)
async def get_server_status(server_name: str = Path(..., description="服务器名称")):
    """
    获取特定MCP服务器状态
    
    Args:
        server_name: 服务器名称
        
    Returns:
        服务器状态信息
    """
    try:
        status = mcp_service_manager.get_server_status(server_name)
        return status
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取服务器状态失败: {str(e)}")


@router.post("/refresh")
async def refresh_configs():
    """
    刷新所有MCP服务器配置
    
    Returns:
        刷新结果
    """
    try:
        # 重新初始化MCP配置
        settings.init_mcp_configs()
        return {"message": "MCP服务器配置刷新成功"}
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"刷新配置失败: {str(e)}")


@router.get("/health/{server_name}", response_model=HealthCheckResponse)
async def health_check(server_name: str = Path(..., description="服务器名称")):
    """
    检查MCP服务器健康状态
    
    Args:
        server_name: 服务器名称
        
    Returns:
        健康检查结果
    """
    try:
        result = await mcp_service_manager.health_check(server_name)
        return HealthCheckResponse(**result)
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"健康检查失败: {str(e)}")


@router.get("/health", response_model=List[HealthCheckResponse])
async def health_check_all():
    """
    检查所有MCP服务器健康状态
    
    Returns:
        所有服务器的健康检查结果
    """
    try:
        results = []
        for server_name in settings.MCP_SERVERS:
            result = await mcp_service_manager.health_check(server_name)
            results.append(HealthCheckResponse(**result))
        return results
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"健康检查失败: {str(e)}")


# FastMCP管理接口
@router.post("/manager")
async def fastmcp_manager(request: FastMCPManagerRequest):
    """
    FastMCP管理接口
    
    Args:
        request: 管理请求
        
    Returns:
        操作结果
    """
    try:
        action = request.action
        parameters = request.parameters
        
        loop = asyncio.get_event_loop()
        
        if action == "register_server":
            result = await fast_register_server(**parameters)
        elif action == "unregister_server":
            result = await fast_unregister_server(**parameters)
        elif action == "list_servers":
            result = await fast_list_servers(**parameters)
        elif action == "get_server_info":
            result = await fast_get_server_info(**parameters)
        elif action == "check_health":
            result = await fast_check_health(**parameters)
        elif action == "discover_tools":
            result = await fast_discover_tools(**parameters)
        elif action == "invoke_tool":
            result = await fast_invoke_tool(**parameters)
        else:
            raise HTTPException(status_code=400, detail=f"未知操作: {action}")
            
        return {"result": result}
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"执行管理操作失败: {str(e)}")


@router.get("/plugins/cache/{plugin_name}", response_model=PluginCacheInfo)
async def get_plugin_cache_info(plugin_name: str = Path(..., description="插件名称")):
    """
    获取插件缓存信息
    
    Args:
        plugin_name: 插件名称
        
    Returns:
        插件缓存信息
    """
    try:
        # 检查插件是否在缓存中
        is_cached = plugin_name in plugin_loader.plugin_cache
        is_valid = None
        timestamp = None
        
        if is_cached:
            is_valid = plugin_loader._is_cache_valid(plugin_name)
            timestamp = plugin_loader.plugin_cache_timestamps.get(plugin_name)
        
        return PluginCacheInfo(
            plugin_name=plugin_name,
            cached=is_cached,
            valid=is_valid,
            timestamp=timestamp,
            ttl=plugin_loader.plugin_cache_ttl
        )
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取插件缓存信息失败: {str(e)}")


@router.post("/plugins/cache/clear")
async def clear_plugin_cache():
    """
    清除插件缓存
    
    Returns:
        操作结果
    """
    try:
        count = len(plugin_loader.plugin_cache)
        plugin_loader.plugin_cache.clear()
        plugin_loader.plugin_cache_timestamps.clear()
        
        return {
            "success": True,
            "message": f"已清除 {count} 个插件缓存项",
            "cleared_count": count
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"清除插件缓存失败: {str(e)}")


@router.post("/plugins/load-all-async")
async def load_all_plugins_async():
    """
    异步加载所有插件
    
    Returns:
        加载结果
    """
    try:
        await plugin_loader.load_all_plugins_async()
        return {
            "success": True,
            "message": "所有插件异步加载完成"
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"异步加载插件失败: {str(e)}")


@router.post("/plugins/{plugin_name}/register-async")
async def register_plugin_async(plugin_name: str = Path(..., description="插件名称")):
    """
    异步注册插件
    
    Args:
        plugin_name: 插件名称
        
    Returns:
        注册结果
    """
    try:
        success = await plugin_loader.register_plugin_async(plugin_name)
        if success:
            return {
                "success": True,
                "message": f"插件 {plugin_name} 异步注册成功",
                "plugin": plugin_name
            }
        else:
            raise HTTPException(status_code=500, detail=f"插件 {plugin_name} 异步注册失败")
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"异步注册插件失败: {str(e)}")


@router.get("/remote-plugins-async")
async def discover_remote_plugins_async():
    """
    异步发现远程插件
    
    Returns:
        远程插件列表
    """
    try:
        remote_plugins = await plugin_loader.discover_remote_plugins_async()
        return {"plugins": remote_plugins}
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"异步发现远程插件失败: {str(e)}")


@router.post("/plugins/{plugin_name}/initialize")
async def initialize_plugin(plugin_name: str = Path(..., description="插件名称")):
    """
    初始化插件
    
    Args:
        plugin_name: 插件名称
        
    Returns:
        初始化结果
    """
    try:
        success = plugin_loader.initialize_plugin(plugin_name)
        if success:
            return {
                "success": True,
                "message": f"插件 {plugin_name} 初始化成功",
                "plugin": plugin_name
            }
        else:
            raise HTTPException(status_code=500, detail=f"插件 {plugin_name} 初始化失败")
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"初始化插件失败: {str(e)}")


@router.post("/plugins/{plugin_name}/start")
async def start_plugin(plugin_name: str = Path(..., description="插件名称")):
    """
    启动插件
    
    Args:
        plugin_name: 插件名称
        
    Returns:
        启动结果
    """
    try:
        success = plugin_loader.start_plugin(plugin_name)
        if success:
            return {
                "success": True,
                "message": f"插件 {plugin_name} 启动成功",
                "plugin": plugin_name
            }
        else:
            raise HTTPException(status_code=500, detail=f"插件 {plugin_name} 启动失败")
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"启动插件失败: {str(e)}")


@router.post("/plugins/{plugin_name}/pause")
async def pause_plugin(plugin_name: str = Path(..., description="插件名称")):
    """
    暂停插件
    
    Args:
        plugin_name: 插件名称
        
    Returns:
        暂停结果
    """
    try:
        success = plugin_loader.pause_plugin(plugin_name)
        if success:
            return {
                "success": True,
                "message": f"插件 {plugin_name} 暂停成功",
                "plugin": plugin_name
            }
        else:
            raise HTTPException(status_code=500, detail=f"插件 {plugin_name} 暂停失败")
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"暂停插件失败: {str(e)}")


@router.post("/plugins/{plugin_name}/resume")
async def resume_plugin(plugin_name: str = Path(..., description="插件名称")):
    """
    恢复插件
    
    Args:
        plugin_name: 插件名称
        
    Returns:
        恢复结果
    """
    try:
        success = plugin_loader.resume_plugin(plugin_name)
        if success:
            return {
                "success": True,
                "message": f"插件 {plugin_name} 恢复成功",
                "plugin": plugin_name
            }
        else:
            raise HTTPException(status_code=500, detail=f"插件 {plugin_name} 恢复失败")
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"恢复插件失败: {str(e)}")


@router.post("/plugins/{plugin_name}/stop")
async def stop_plugin(plugin_name: str = Path(..., description="插件名称")):
    """
    停止插件
    
    Args:
        plugin_name: 插件名称
        
    Returns:
        停止结果
    """
    try:
        success = plugin_loader.stop_plugin(plugin_name)
        if success:
            return {
                "success": True,
                "message": f"插件 {plugin_name} 停止成功",
                "plugin": plugin_name
            }
        else:
            raise HTTPException(status_code=500, detail=f"插件 {plugin_name} 停止失败")
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"停止插件失败: {str(e)}")


@router.post("/plugins/{plugin_name}/restart")
async def restart_plugin(plugin_name: str = Path(..., description="插件名称")):
    """
    重启插件
    
    Args:
        plugin_name: 插件名称
        
    Returns:
        重启结果
    """
    try:
        success = plugin_loader.restart_plugin(plugin_name)
        if success:
            return {
                "success": True,
                "message": f"插件 {plugin_name} 重启成功",
                "plugin": plugin_name
            }
        else:
            raise HTTPException(status_code=500, detail=f"插件 {plugin_name} 重启失败")
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"重启插件失败: {str(e)}")


@router.post("/plugins/lifecycle-hook")
async def add_lifecycle_hook(
    plugin_name: str = Body(..., embed=True),
    hook_type: str = Body(..., embed=True),
    hook_func: str = Body(..., embed=True)  # 实际使用中可能需要更复杂的处理
):
    """
    添加插件生命周期钩子
    
    Args:
        plugin_name: 插件名称
        hook_type: 钩子类型
        hook_func: 钩子函数标识
        
    Returns:
        添加结果
    """
    try:
        # 这里只是一个示例实现，实际使用中可能需要更复杂的处理
        # 比如通过反射获取函数或者通过其他方式注册
        def dummy_hook():
            print(f"执行 {plugin_name} 的 {hook_type} 钩子")
        
        plugin_loader.add_lifecycle_hook(plugin_name, hook_type, dummy_hook)
        
        return {
            "success": True,
            "message": f"为插件 {plugin_name} 添加 {hook_type} 钩子成功"
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"添加生命周期钩子失败: {str(e)}")


@router.post("/plugins/event-listener")
async def add_event_listener(
    event_type: str = Body(..., embed=True),
    listener_func: str = Body(..., embed=True)  # 实际使用中可能需要更复杂的处理
):
    """
    添加事件监听器
    
    Args:
        event_type: 事件类型
        listener_func: 监听器函数标识
        
    Returns:
        添加结果
    """
    try:
        # 这里只是一个示例实现，实际使用中可能需要更复杂的处理
        def dummy_listener(data):
            print(f"处理 {event_type} 事件: {data}")
        
        plugin_loader.add_event_listener(event_type, dummy_listener)
        
        return {
            "success": True,
            "message": f"添加 {event_type} 事件监听器成功"
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"添加事件监听器失败: {str(e)}")


class PluginDependenciesResponse(BaseModel):
    """插件依赖响应模型"""
    plugin: str
    dependencies: List[str]
    resolved_dependencies: Optional[List[str]] = None


@router.get("/plugins/{plugin_name}/dependencies", response_model=PluginDependenciesResponse)
async def get_plugin_dependencies(plugin_name: str = Path(..., description="插件名称")):
    """
    获取插件依赖关系
    
    Args:
        plugin_name: 插件名称
        
    Returns:
        插件依赖信息
    """
    try:
        dependencies = plugin_loader.get_plugin_dependencies(plugin_name)
        return PluginDependenciesResponse(
            plugin=plugin_name,
            dependencies=dependencies
        )
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取插件依赖失败: {str(e)}")


@router.post("/plugins/load-all-ordered")
async def load_all_plugins_ordered():
    """
    按依赖顺序加载所有插件
    
    Returns:
        加载结果
    """
    try:
        plugin_loader.load_all_plugins()
        return {
            "success": True,
            "message": "所有插件按依赖顺序加载完成"
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"按依赖顺序加载插件失败: {str(e)}")


@router.post("/plugins/load-all-ordered-async")
async def load_all_plugins_ordered_async():
    """
    异步按依赖顺序加载所有插件
    
    Returns:
        加载结果
    """
    try:
        await plugin_loader.load_all_plugins_async()
        return {
            "success": True,
            "message": "所有插件按依赖顺序异步加载完成"
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"按依赖顺序异步加载插件失败: {str(e)}")


@router.get("/errors/latest", response_model=List[ErrorDetailsResponse])
async def get_latest_errors(limit: int = Query(10, ge=1, le=100)):
    """
    获取最新的错误信息
    
    Args:
        limit: 返回错误数量限制
        
    Returns:
        最新的错误信息列表
    """
    # 注意：在实际生产环境中，错误信息应该存储在日志系统或数据库中
    # 这里只是一个示例实现
    return []


@router.post("/plugins/{plugin_name}/recover")
async def recover_plugin(plugin_name: str = Path(..., description="插件名称")):
    """
    尝试恢复插件到正常状态
    
    Args:
        plugin_name: 插件名称
        
    Returns:
        恢复结果
    """
    try:
        # 检查插件当前状态
        current_state = plugin_loader.plugin_states.get(plugin_name, "unknown")
        
        # 根据当前状态执行恢复操作
        if current_state == plugin_loader.PLUGIN_STATE_ERROR:
            # 如果插件处于错误状态，尝试重启
            if plugin_loader.restart_plugin(plugin_name):
                return {
                    "success": True,
                    "message": f"插件 {plugin_name} 恢复成功",
                    "plugin": plugin_name,
                    "previous_state": current_state,
                    "new_state": plugin_loader.plugin_states.get(plugin_name)
                }
            else:
                raise HTTPException(status_code=500, detail=f"插件 {plugin_name} 恢复失败")
        elif current_state == plugin_loader.PLUGIN_STATE_STOPPED:
            # 如果插件已停止，尝试启动
            if plugin_loader.start_plugin(plugin_name):
                return {
                    "success": True,
                    "message": f"插件 {plugin_name} 启动成功",
                    "plugin": plugin_name,
                    "previous_state": current_state,
                    "new_state": plugin_loader.plugin_states.get(plugin_name)
                }
            else:
                raise HTTPException(status_code=500, detail=f"插件 {plugin_name} 启动失败")
        elif current_state == plugin_loader.PLUGIN_STATE_PAUSED:
            # 如果插件已暂停，尝试恢复
            if plugin_loader.resume_plugin(plugin_name):
                return {
                    "success": True,
                    "message": f"插件 {plugin_name} 恢复运行成功",
                    "plugin": plugin_name,
                    "previous_state": current_state,
                    "new_state": plugin_loader.plugin_states.get(plugin_name)
                }
            else:
                raise HTTPException(status_code=500, detail=f"插件 {plugin_name} 恢复运行失败")
        else:
            return {
                "success": True,
                "message": f"插件 {plugin_name} 状态正常，无需恢复",
                "plugin": plugin_name,
                "state": current_state
            }
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"恢复插件失败: {str(e)}")


@router.post("/plugins/{plugin_name}/reset")
async def reset_plugin(plugin_name: str = Path(..., description="插件名称")):
    """
    重置插件（卸载后重新加载）
    
    Args:
        plugin_name: 插件名称
        
    Returns:
        重置结果
    """
    try:
        # 卸载插件
        if not plugin_loader.unload_plugin(plugin_name):
            raise HTTPException(status_code=500, detail=f"卸载插件 {plugin_name} 失败")
        
        # 重新加载插件
        if plugin_loader.register_plugin(plugin_name):
            return {
                "success": True,
                "message": f"插件 {plugin_name} 重置成功",
                "plugin": plugin_name,
                "state": plugin_loader.plugin_states.get(plugin_name)
            }
        else:
            raise HTTPException(status_code=500, detail=f"重新加载插件 {plugin_name} 失败")
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"重置插件失败: {str(e)}")


@router.post("/feedback", response_model=PluginFeedbackResponse)
async def add_plugin_feedback(feedback_request: PluginFeedbackRequest):
    """
    添加插件反馈
    
    Args:
        feedback_request: 反馈请求数据
        
    Returns:
        反馈添加结果
    """
    try:
        result = mcp_service_manager.add_feedback(
            server_name=feedback_request.server_name,
            user_id=feedback_request.user_id,
            feedback=feedback_request.feedback,
            feedback_type=feedback_request.feedback_type,
            metadata=feedback_request.metadata,
            priority=feedback_request.priority
        )
        
        if result["success"]:
            return PluginFeedbackResponse(
                success=True,
                message=result["message"],
                feedback_id=result["feedback_id"]
            )
        else:
            return PluginFeedbackResponse(
                success=False,
                message="添加反馈失败",
                error=result["error"]
            )
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"添加反馈失败: {str(e)}")


@router.get("/feedback/{server_name}", response_model=FeedbackHistoryResponse)
async def get_feedback_history(server_name: str = Path(..., description="服务器名称")):
    """
    获取服务器反馈历史
    
    Args:
        server_name: 服务器名称
        
    Returns:
        反馈历史
    """
    try:
        feedback_list = mcp_service_manager.get_feedback_history(server_name)
        return FeedbackHistoryResponse(
            server_name=server_name,
            feedback_list=feedback_list
        )
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取反馈历史失败: {str(e)}")


@router.post("/feedback/process", response_model=FeedbackProcessResponse)
async def process_feedback(process_request: FeedbackProcessRequest):
    """
    处理服务器反馈
    
    Args:
        process_request: 反馈处理请求
        
    Returns:
        处理结果
    """
    try:
        result = mcp_service_manager.process_feedback(
            server_name=process_request.server_name,
            strategy=process_request.strategy,
            custom_thresholds=process_request.custom_thresholds
        )
        
        if result["success"]:
            return FeedbackProcessResponse(
                success=True,
                message=result["message"],
                feedback_analysis=result.get("feedback_analysis"),
                actions_taken=result.get("actions_taken")
            )
        else:
            return FeedbackProcessResponse(
                success=False,
                message="处理反馈失败",
                error=result["error"]
            )
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"处理反馈失败: {str(e)}")


@router.get("/feedback/summary/{server_name}", response_model=FeedbackSummaryResponse)
async def get_feedback_summary(server_name: str = Path(..., description="服务器名称")):
    """
    获取服务器反馈摘要
    
    Args:
        server_name: 服务器名称
        
    Returns:
        反馈摘要
    """
    try:
        summary = mcp_service_manager.get_feedback_summary(server_name)
        return FeedbackSummaryResponse(**summary)
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取反馈摘要失败: {str(e)}")
